# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from scrapy.http.headers import Headers

import urllib.request as ur

from zhaobiao.proxypool import ProxyPool


class ZhaobiaoSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ZhaobiaoDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    def __init__(self):
        self.proxyPool = ProxyPool()

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # request.meta['proxy'] = 'http://' + ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=66d0a1878885b01032f307ae83e22b30&sep=3').read().decode('utf-8').strip()
        # request.headers = Headers(
        #     {
        #         'Cookie': 'UM_distinctid=16cdd82d275614-0d4c8d437a7ca3-7373e61-1fa400-16cdd82d276899; selectNum=1; SESSIONID=13dff80cccf803fbab5e46c621b3ac958e942584; SESSIONID=13dff80cccf803fbab5e46c621b3ac958e942584; CNZZDATA1261815924=1061752773-1567084434-https%253A%252F%252Fwww.google.com%252F%7C1567134311; Hm_lvt_72331746d85dcac3dac65202d103e5d9=1567084434,1567090121,1567138456; Hm_lpvt_72331746d85dcac3dac65202d103e5d9=1567138456; userid_secure=LCmslM91de/vZ9xpPgxlhDt1huw9l8IKExRn3rBLNIXQk6839qI6TdB2Em8tZo2xPy2NIiWvJ28kWwrLB+DENuaXnhxkCziAibA9K4b/MvEv28Bzzh0GS8YPVlGQP74MrTRtuqfn+CT7jspblaK4XP/Jat8blb/Uwtq6sWexYxfOzMaHMl4zdbA1/vLgffbqJKh13coL7GdVHsa6/QEMpjw2l4QXNZGZCqXxhB0wfq/JcoKh21UDItWT3OIFzdQBsNXzAfPQ7lZBJbvhn2+rkxPC792kQ77Qnwpqp3vaycfBTwdDdnu37ojjdAeH4//YjhJt3y6rBNFHafRm/LPGAioqKjIwMTktMDgtMjUgMDA6MDA6MDA=',
        #     }
        # )

        request.meta['proxy'] = 'http://' + self.proxyPool.get_proxy()
        # print(request.meta['proxy'])

        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
